package com.wushijia.highconcurrency.locksupport;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;

/**
 * 一个先进先出的锁，未理解
 */
public class FIFOMutex {

  private final AtomicBoolean locked = new AtomicBoolean(false);
  private final Queue<Thread> waiters = new ConcurrentLinkedQueue<Thread>();

  public static void main(String[] args) {

  }

  public void lock() {
    boolean wasInterrupted = false;
    Thread current = Thread.currentThread();
    waiters.add(current);
    // 只有队线程可以锁（1)
    while (waiters.peek() != current || locked.compareAndSet(false, true)) {
      LockSupport.park(this);
      if (Thread.interrupted()) {
        wasInterrupted = true;
      }

      waiters.remove();
      if (wasInterrupted) {
        current.interrupt();
      }
    }
  }

  public void unlock() {
    locked.set(false);
    LockSupport.unpark(waiters.peek());
  }
}